
#include "osal_thread.h"
#include "osal_memory.h"

osal_thread_t *osal_thread_init( const char *name,
                                        void (*entry)(void *),
                                        void * const param,
                                        unsigned int stack_size,
                                        unsigned int priority,
                                        unsigned int tick)
{
    int res;
    osal_thread_t *thread;
    void *(*thread_entry) (void *);

    thread_entry = (void *(*)(void*))entry;
    thread = osal_memory_alloc(sizeof(osal_thread_t));
    
    res = pthread_create(&thread->thread, NULL, thread_entry, param);
    if(res != 0) {
        osal_memory_free(thread);
    }

    thread->mutex = (pthread_mutex_t)PTHREAD_MUTEX_INITIALIZER;
    thread->cond = (pthread_cond_t)PTHREAD_COND_INITIALIZER;

    return thread;
}

void osal_thread_startup(osal_thread_t* thread)
{
    (void) thread;
}

void osal_thread_stop(osal_thread_t* thread)
{
    pthread_mutex_lock(&(thread->mutex));
    pthread_cond_wait(&(thread->cond), &(thread->mutex));
    pthread_mutex_unlock(&(thread->mutex));
}

void osal_thread_start(osal_thread_t* thread)
{
    pthread_mutex_lock(&(thread->mutex)); 
    pthread_cond_signal(&(thread->cond));
    pthread_mutex_unlock(&(thread->mutex));
}

void osal_thread_destroy(osal_thread_t* thread)
{
    if (NULL != thread)
        pthread_detach(thread->thread);
}


